import React, { useMemo, useRef } from "react";
import { useEffect, useState } from "react";
import axios from "axios";
import { SidebarAdmin } from "../../components/Sidebar";
import "./useradministrator.css";
import { AddUserRole, GetUserInfo, GetUserRoleList } from "../../api";
import { IUserInfo, IUserRoles } from "../../utils/constant";
import { Form, FormInstance, Input, Modal, Select } from "antd";
const formRules = [{ required: true }];

const roles = [
  {
    roleId: 1,
    roleName: "Admin", // to be replaced with "Super Admin" if there is a need for it
  },
  {
    roleId: 2,
    roleName: "Admin",
  },
  {
    roleId: 3,
    roleName: "Staff",
  },
  {
    roleId: 4,
    roleName: "Student",
  },
]


export const UserAdminstrator: React.FC = () => {
  const [saRoleCheck, setSaRoleCheck] = useState(false);
  const [userRoleList, setUserRoleList] = useState<IUserRoles[]>([]);
  const [userInfo, setUserInfo] = useState<IUserInfo[]>([]);
  const [isAddModalOpen, setIsAddModalOpen] = useState<boolean>(false);
  const [addRoleData, setAddRoleData] = useState({ email: "", role: "" });
  const formRef = useRef<FormInstance>(null);

  //check if admin is already logged in
  const fetchSaRoleCheck = async () => {
    axios({
      method: "GET",
      headers: { satoken: window.localStorage.getItem("satoken") },
      url: "http://localhost:8080/user/administrator",
    }).then((res) => {
      if (res.data.success) {
        setSaRoleCheck(true);
      } else {
        setSaRoleCheck(false);
      }
    });
  }

  const fetchUserRoleList = async () => {
    try {
      const {
        data: { data },
      } = await GetUserRoleList();
      setUserRoleList(data.list);
    } catch (e) {
      console.error(e);
    }
  };

  const fetchUserInfo = async () => {
    try {
      const {
        data: { data },
      } = await GetUserInfo();
      setUserInfo(data.list);
    } catch (e) {
      console.error(e);
    }
  };

  // toggle add admin / staff pop up form
  const openAddModal = () => {
    setIsAddModalOpen(true);
  };

  const closeAddModal = () => {
    setIsAddModalOpen(false);
  };

  const submitButtonStatus = useMemo(() => {
    const { email, role } = addRoleData || {};
    return email && role;
  }, [addRoleData]);

  const handleAddRole = async () => {
    try {
      const userId = userInfo.find(obj => { return obj.email === addRoleData.email })?.id ?? -1;
      const roleId = roles.find(obj => { return obj.roleName === addRoleData.role })?.roleId ?? -1;
      if (userId === -1) {
        alert("Account with this email does not exist!");
        return
      }
      if (roleId === -1) {
        alert("Role does not exist!");
        return
      }
      const res = await AddUserRole(userId, roleId);
      if (res.data.success) {
        closeAddModal();
        formRef.current?.resetFields();
        fetchUserRoleList();
      }
      else {
        alert(res.data.msg);
      }
    } catch (e) {
      console.error(e);
    }
  };

  const handleEditRole = (changevalue: any, values: any) => {
    setAddRoleData(values);
  };

  const deleteConfirm = (userId: number) => {
    Modal.confirm({
      title: "Are you sure you want to remove user role?",
      okText: "Yes",
      cancelText: "Cancel",
      onOk: async () => {
        const res = await AddUserRole(userId, 4);
        if (res.data.success) {
          fetchUserRoleList();
        }
        else {
          alert(res.data.msg);
        }
      },
    });
  };


  useEffect(() => {
    fetchSaRoleCheck();
    fetchUserRoleList();
    fetchUserInfo();
  }, []); // initial render


  if (saRoleCheck) {
    return (
      <>
        <SidebarAdmin />
        <div className="user-role">
          <h4>Administrator & Staff Accounts:</h4>
          <table id="user-role-table">
            <thead>
              <tr>
                <th>User Id</th>
                <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {userRoleList.map((val, key) => {
                return (val.roleId === 1 || val.roleId === 2 || val.roleId === 3 ? (
                  <tr key={key}>
                    <td>{val.userId}</td>
                    <td>{userInfo.find(obj => {
                      return obj.id === val.userId
                    })?.name}
                    </td>
                    <td>{userInfo.find(obj => {
                      return obj.id === val.userId
                    })?.email}
                    </td>
                    <td>{
                      roles.find(obj => {
                        return obj.roleId === val.roleId
                      })?.roleName}</td>
                    <td>
                      <button
                        id="change-role-button"
                        onClick={() => {
                          deleteConfirm(val.userId);
                        }}
                      >Revoke
                      </button>
                    </td>
                  </tr>) : (<tr></tr>)
                );
              })}
            </tbody>
          </table>

          <button
            id="addAdministrator"
            onClick={openAddModal}
          >+ Add Administrator / Staff
          </button>
        </div>

        <Modal
          title="Add User Role"
          open={isAddModalOpen}
          onCancel={closeAddModal}
          onOk={handleAddRole}
          okButtonProps={{ disabled: !submitButtonStatus }}
        >
          <Form ref={formRef} onValuesChange={handleEditRole}>
            <Form.Item required label="Email" name="email" rules={formRules}>
              <Input></Input>
            </Form.Item>
            <Form.Item required label="Role" name="role" rules={formRules}>
              <Select
                onChange={() => { handleEditRole }}
                options={[
                  { value: 'Admin', label: 'Admin' },
                  { value: 'Staff', label: 'Staff' },
                ]}>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

      </>
    );
  } else {
    return <></>;
  }
};
